package com.googlecode.lookie.platform.osgi;

import java.awt.Image;
import java.util.ArrayList;
import java.util.List;

import org.springframework.context.support.ApplicationObjectSupport;
import org.springframework.richclient.image.AwtImageResource;
import org.springframework.richclient.image.ImageSource;
import org.springframework.richclient.image.NoSuchImageResourceException;

public class OsgiImageSource
    extends ApplicationObjectSupport
    implements ImageSource
{

    private ImageSource[] imageSources;

    public ImageSource[] getImageSources()
    {
        if ( true )
        {
            List<ImageSource> list = new ArrayList<ImageSource>();

            Object osgiBeans = getApplicationContext().getBean( "imageSources" );
            for ( Object bean : ( (List<?>) osgiBeans ) )
            {
                ImageSource source = (ImageSource) bean;
                list.add( source );
            }

            imageSources = list.toArray( new ImageSource[list.size()] );
        }

        return imageSources;
    }

    public Image getImage( String key )
    {
        Image image = null;

        for ( ImageSource source : getImageSources() )
        {
            try
            {
                image = source.getImage( key );
            }
            catch ( RuntimeException e )
            {
            }
            if ( image != null )
            {
                break;
            }
        }

        if ( image == null )
        {
            throw new NoSuchImageResourceException( key );
        }

        return image;
    }

    public AwtImageResource getImageResource( String key )
    {
        AwtImageResource image = null;

        for ( ImageSource source : getImageSources() )
        {
            try
            {
                image = source.getImageResource( key );
            }
            catch ( RuntimeException e )
            {
            }
            if ( image != null )
            {
                break;
            }
        }

        if ( image == null )
        {
            throw new NoSuchImageResourceException( key );
        }

        return image;
    }

}
